source('base.R')

log_list <- c('daily_log_2011-04-04', 'daily_log_2011-04-05', 'daily_log_2011-04-06', 
              'daily_log_2011-04-08', 'daily_log_2011-04-09', 'daily_log_2011-04-10',
              'daily_log_2011-04-11', 'daily_log_2011-04-13')

get_action <- function(action_data, action_name) {
    action_table = table(action_data)
    ifelse(action_name %in% names(action_table), action <- action_table[action_name], action <- 0 )
    return(action)
}

regression <- function(data, sig_min, sig_max, sample_size) {
    pop <- nlevels(factor(data$user_id))
    breaks <- seq(from=1, to=pop, length=sample_size)

    x <- data$action[breaks]
    y <- seq(from=sig_min, to=sig_max, length=sample_size)
    a <- sig_max
    b <- log(sig_min/sig_max)

    gompertz <- nls(y ~ a * exp(b * exp(c * x)), start=list(c=-1))
    summary(gompertz)
}

run <- function(log_filename) {
    log <- read(log_filename)
    
    play <- tapply(log$action, INDEX=log$user_id, FUN=get_action, action_name='p')
    skip <- tapply(log$action, INDEX=log$user_id, FUN=get_action, action_name='s')

    p_data <- data.frame(user_id=levels(factor(log$user_id)))
    p_data$action <- play[as.character(p_data$user_id)]
    p_data <- p_data[p_data$action != 0,]
    p_data <- p_data[order(p_data$action),]

    s_data <- data.frame(user_id=levels(factor(log$user_id)))
    s_data$action <- skip[as.character(s_data$user_id)]
    s_data <- s_data[s_data$action != 0,]
    s_data <- s_data[order(s_data$action),]

    regression(p_data, 1, 2, 1000)
    regression(s_data, 1, 2, 1000)
}

#sink('gompertz.output')
#lapply(log_list, FUN=run)
#run('data/daily_log_2011-04-04')
#sink()
